package com.itouch.bracelet.activity;

import io.rong.imkit.RongIM;

import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.itouch.bracelet.R;
import com.itouch.bracelet.bean.Child;
import com.itouch.bracelet.bean.LoginUser;
import com.itouch.bracelet.bean.UpdateInfo;
import com.itouch.bracelet.bluetooth.BluetoothConstants;
import com.itouch.bracelet.bluetooth.BluetoothHandler;
import com.itouch.bracelet.bluetooth.BluetoothPacket;
import com.itouch.bracelet.bluetooth.BluetoothType;
import com.itouch.bracelet.bluetooth.BluetoothUtil;
import com.itouch.bracelet.bluetooth.BluetoothValue;
import com.itouch.bracelet.cache.UserCache;
import com.itouch.bracelet.diseaseinfo.Constants;
import com.itouch.bracelet.diseaseinfo.DiseaseInfoActivity;
import com.itouch.util.CoFileUtil;
import com.itouch.util.MethodUtils;
import com.itouch.widget.ActionSheet;
import com.itouch.widget.ActionSheet.ActionSheetListener;
import com.itouch.widget.CircleLayout;
import com.itouch.widget.RoundedImageView;
import com.itouch.widget.autoscrollviewpager.AutoScrollViewPager;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;

public class MainActivity extends SMBaseActivity implements OnClickListener,
		SlidingMenu.OnClosedListener, ActionSheetListener {

	private RoundedImageView mainLeftIcon;
	private RoundedImageView mainRightIcon;
	private LinearLayout bottombarMsg;
	private ImageView bottombarCenter;
	private LinearLayout bottombarSet;
	private RelativeLayout zero2one;
	private CircleLayout circlelayout;
	private AutoScrollViewPager pager;
	private ImageView[] imgArray = new ImageView[Constants.VP_NUMBER];// viewpager
	private String cacheDir = Environment.getExternalStorageDirectory()
			+ Constants.PATH_PICTURE; // 对应的下表爱心图片的4个控件的集合
	private ImageView vpi_1;
	private ImageView vpi_2;
	private ImageView vpi_3;
	private ImageView vpi_4;// viewpager 对应的下表爱心图片的4个控件

	private String[] cacheImageMame = { "img1.jpg", "img2.jpg", "img3.jpg",
			"img4.jpg" }; // viewpager 的缓存图片的名字

	private String[] imgs = { "file://" + cacheDir + "/" + "img1.jpg",
			"file://" + cacheDir + "/" + "img2.jpg",
			"file://" + cacheDir + "/" + "img3.jpg",
			"file://" + cacheDir + "/" + "img4.jpg" };
	
	private int viewPagerImagePosition;// 用于记录需要更换第几张图片

	private static final int REQUEST_CAMERA = 1003;
	private static final int REQUEST_PICTURE = 1004;
	private static final int PHOTO_CODE = 1005;
	
	private Uri uri = null;
	private DisplayImageOptions left_options;
	private DisplayImageOptions right_options;
	private ImageLoader imageLoader=ImageLoader.getInstance();
	
	private DisplayImageOptions options;
	private PageAdapter pagerAdapter;
	private FadeInBitmapDisplayer fadeInBitmapDisplayer;
	
	
	public MainActivity() {
		super(R.string.app_name);
	}
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getSlidingMenu().setMode(SlidingMenu.LEFT_RIGHT);
		getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
		setContentView(R.layout.activity_main);
		getSlidingMenu().setSecondaryMenu(R.layout.menu_frame_two);
		getSlidingMenu().setSecondaryShadowDrawable(R.drawable.shadowright);
		getSlidingMenu().setOnClosedListener(this);
		getSupportFragmentManager().beginTransaction()
				.replace(R.id.menu_frame_two, new MainRightFragment()).commit();
		initViews();
		
		
		//加载蓝牙设置值
		// init status
		if (BluetoothValue.INSTANCE.temperatureStatus == null) {

			SharedPreferences sp = getSharedPreferences("Bluetooth",
					this.MODE_PRIVATE);
			
			BluetoothValue.INSTANCE.temperatureStatus = sp.getBoolean(
					"temperature", true);
			BluetoothValue.INSTANCE.lowEnergyStatus = sp.getBoolean(
					"lowenergy", true);
			BluetoothValue.INSTANCE.lostStatus = sp.getBoolean("lost", true);
			
			BluetoothValue.INSTANCE.outOfRangeStatus = sp.getBoolean("outofrange", true);

		}
		
		//订阅广播
		
		IntentFilter filter = new IntentFilter();
		filter.addAction(BluetoothHandler.ACTION_STATUS);
		filter.addAction(BluetoothHandler.ACTION_DATA);
		registerReceiver(receiver, filter);
		
	}

	private void initViews() {
		 fadeInBitmapDisplayer = new FadeInBitmapDisplayer(300);
		
		//viewpager图片的加载设置
		options = new DisplayImageOptions.Builder()
		.showImageForEmptyUri(R.drawable.banner)
		.showImageOnFail(R.drawable.banner)
		.resetViewBeforeLoading(false)
		.cacheInMemory(true).imageScaleType(ImageScaleType.EXACTLY)
		.bitmapConfig(Bitmap.Config.RGB_565).considerExifParams(true)
		.displayer(fadeInBitmapDisplayer).build();
		//妈妈头像的加载设置
		left_options = new DisplayImageOptions.Builder()
		.showImageForEmptyUri(R.drawable.main_left_icon)
		.showImageOnFail(R.drawable.main_left_icon)
		.resetViewBeforeLoading(true).cacheOnDisc(true)
		.imageScaleType(ImageScaleType.EXACTLY)
		.bitmapConfig(Bitmap.Config.RGB_565).considerExifParams(true)
		.displayer(fadeInBitmapDisplayer).build();
		//小孩头像的加载设置
		right_options = new DisplayImageOptions.Builder()
		.showImageForEmptyUri(R.drawable.main_right_icon)
		.showImageOnFail(R.drawable.main_right_icon)
		.resetViewBeforeLoading(true).cacheOnDisc(true)
		.imageScaleType(ImageScaleType.EXACTLY)
		.bitmapConfig(Bitmap.Config.RGB_565).considerExifParams(true)
		.displayer(fadeInBitmapDisplayer).build();
		
		
		imgArray[0] = (ImageView) findViewById(R.id.vpi_1);
		imgArray[1] = (ImageView) findViewById(R.id.vpi_2);
		imgArray[2] = (ImageView) findViewById(R.id.vpi_3);
		imgArray[3] = (ImageView) findViewById(R.id.vpi_4);

		mainLeftIcon = (RoundedImageView) findViewById(R.id.main_left_icon);
		mainRightIcon = (RoundedImageView) findViewById(R.id.main_right_icon);
		bottombarMsg = (LinearLayout) findViewById(R.id.bottombar_msg);
		bottombarCenter = (ImageView) findViewById(R.id.bottombar_center);
		bottombarSet = (LinearLayout) findViewById(R.id.bottombar_set);
		// zero2one = (RelativeLayout)findViewById( R.id.zero2one );
		// zero2one.setOnClickListener(this);
		circlelayout = (CircleLayout) findViewById(R.id.circlelayout);
		mainLeftIcon.setOnClickListener(this);
		mainRightIcon.setOnClickListener(this);
		bottombarMsg.setOnClickListener(this);
		bottombarCenter.setOnClickListener(this);
		bottombarSet.setOnClickListener(this);

		pager = (AutoScrollViewPager) findViewById(R.id.scroll_pager);

		pagerAdapter = new PageAdapter();
		pager.setAdapter(pagerAdapter);

		pager.setScrollFactgor(5);
		pager.setOffscreenPageLimit(4);
		pager.startAutoScroll(4000);
		pager.setOnPageClickListener(new AutoScrollViewPager.OnPageClickListener() {

			@Override
			public void onPageClick(AutoScrollViewPager autoScrollPager,
					int position) {

				viewPagerImagePosition = position;

				setTheme(R.style.ActionSheetStyleIOS7);
				ActionSheet
						.createBuilder(MainActivity.this,
								getSupportFragmentManager())
						.setCancelButtonTitle("取消")
						.setOtherButtonTitles("拍照", "从相册选择")
						.setCancelableOnTouchOutside(true)
						.setListener(MainActivity.this).show();

			}
		});

		pager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int position) {
				getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
				
				changeVPI(position);
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {

			}
		});

	}

	/**
	 * 设置爱心的下标的切换
	 * 
	 * @param position
	 */
	private void changeVPI(int position) {
		if (position < 0 || position >= Constants.VP_NUMBER) {
			return;
		}
		for (int i = 0; i < Constants.VP_NUMBER; i++) {
			if (i == position) {
				imgArray[i].setImageResource(R.drawable.vpi_choose);
			} else {
				imgArray[i].setImageResource(R.drawable.vpi_normal);
			}

		}

	}

	// class Task1 extends AsyncTask<String, String,String>{
	//
	// @Override
	// protected String doInBackground(String... params) {
	// try {
	// Thread.sleep(10*1000);
	// } catch (InterruptedException e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// }
	//
	// return null;
	// }
	//
	// @Override
	// protected void onPostExecute(String result) {
	// // TODO Auto-generated method stub
	// super.onPostExecute(result);
	// circlelayout.setDrawable(R.drawable.status_danger_cry);
	// }
	//
	//
	// }

	@Override
	public void onClick(View v) {
		Intent it = null;
		switch (v.getId()) {
		case R.id.main_left_icon:
			toggle();
			break;
		case R.id.main_right_icon:
			if (!getSlidingMenu().isSecondaryMenuShowing()) {
				getSlidingMenu().showSecondaryMenu();
			} else {
				getSlidingMenu().showContent();
			}

			break;
		case R.id.bottombar_msg:
			RongIM.getInstance().startConversationList(MainActivity.this);
			break;
		case R.id.bottombar_center:

			break;
		case R.id.bottombar_set:
			it = new Intent(this, SetActivity.class);
			startActivity(it);
			break;
		case R.id.contacts:
			it = new Intent(this, ContactActivity.class);
			startActivity(it);
			break;
		case R.id.message:
			it = new Intent(this, MMessageListActivity.class);
			startActivity(it);
			break;
		case R.id.circle:
			Intent in = new Intent(this, FriendCircleActivity.class);
			startActivity(in);
			break;

		case R.id.main_device:
			 it = new Intent(MainActivity.this, MainDeviceActivity.class);
			 startActivity(it);
			break;
		case R.id.knowledge:
			 it = new Intent(MainActivity.this, KnowledgeActivity.class);
			startActivity(it);
			break;

		default:
			break;
		}

	}

	public void gotoDiseaseInfoActivity(int type, String label) {
		Intent intent = new Intent(MainActivity.this, DiseaseInfoActivity.class);
		intent.putExtra("type", type);
		intent.putExtra("label", label);
		startActivity(intent);
	}

	/**
	 * 检查版本
	 */
	private void checkVersion() {
		SharedPreferences settings = getSharedPreferences("ysq_version", 0);
		String updateTime = settings.getString("date", "");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String now = sdf.format(new Date());
		// 检测当天是否已提醒（一天自动提醒一次）
		if (!updateTime.equals(now)) {
			SharedPreferences.Editor editor = settings.edit();
			editor.putString("date", sdf.format(new Date()));
			editor.commit();
			new Thread(CheckVersionTask).start();
		}

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		LoginUser user = UserCache.getOauth(this);
		if (user == null) {
			//无缓存用户，就跳转登陆界面
			Intent it = new Intent(this,LoginActivity.class);
			startActivity(it);
			this.finish();
		} else {
			//设置titlebar 的母亲和孩子的头像
			imageLoader.displayImage(user.getPath(), mainLeftIcon,left_options);
			ArrayList<Child> tempList = user.getChildlist();
			if(tempList!=null&&tempList.size()>0){
				//显示小孩的头像，user.childPosition 为缓存的选中的孩子的位置    
				imageLoader.displayImage(tempList.get(user.childPosition).getPath(), mainRightIcon,right_options);
			}
			//检测版本
			checkVersion();
		}
	}

	/*
	 * 从服务器获取xml解析并进行比对版本号
	 */
	private Runnable CheckVersionTask = new Runnable() {

		@Override
		public void run() {
			try {
				// 从资源文件获取服务器 地址
				String path = Constants.VERSION_XML;
				// 包装成url的对象
				URL url = new URL(path);
				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				conn.setConnectTimeout(5000);
				InputStream is = conn.getInputStream();
				infohaha = MethodUtils.getUpdataInfo(is);

				String versionname = getVersionName();

				if (infohaha.getVersion().equals(versionname)) {

				} else {
					Message msg = new Message();
					msg.what = 0x123456;
					handler.sendMessage(msg);
				}
			} catch (Exception e) {
				// 待处理
				Message msg = new Message();
				msg.what = 0x234567;
				handler.sendMessage(msg);
				e.printStackTrace();
			}
		}
	};

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case 0x123456:
				// 对话框通知用户升级程序
				showUpdataDialog();
				break;
			case 0x234567:
				// 服务器超时
				Toast.makeText(getApplicationContext(), "获取服务器更新信息失败",
						Toast.LENGTH_SHORT).show();
				break;
			case 0x999999:
				// 下载apk失败
				Toast.makeText(getApplicationContext(), "下载新版本失败",
						Toast.LENGTH_SHORT).show();
				break;
			}
		}
	};
	private UpdateInfo infohaha;

	/*
	 * 
	 * 弹出对话框通知用户更新程序
	 * 
	 * 弹出对话框的步骤： 1.创建alertDialog的builder. 2.要给builder设置属性, 对话框的内容,样式,按钮
	 * 3.通过builder 创建一个对话框 4.对话框show()出来
	 */
	protected void showUpdataDialog() {
		AlertDialog.Builder builer = new Builder(this);
		builer.setTitle("版本升级");
		builer.setMessage(infohaha.getDescription());
		// 当点确定按钮时从服务器上下载 新的apk 然后安装
		builer.setPositiveButton("确定", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				downLoadApk();
			}
		});
		builer.setNegativeButton("取消", null);

		AlertDialog dialog = builer.create();
		dialog.show();
	}

	/*
	 * 从服务器中下载APK
	 */
	protected void downLoadApk() {
		final ProgressDialog pd; // 进度条对话框
		pd = new ProgressDialog(this);
		pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		pd.setMessage("正在下载更新");
		pd.show();
		new Thread() {
			@Override
			public void run() {
				try {
					File file = MethodUtils.getFileFromServer(
							Constants.VERSION_APK, pd);
					sleep(3000);
					installApk(file);
					pd.dismiss(); // 结束掉进度条对话框
				} catch (Exception e) {
					Message msg = new Message();
					msg.what = 0x999999;
					handler.sendMessage(msg);
					e.printStackTrace();
					pd.dismiss(); // 结束掉进度条对话框
				}
			}
		}.start();
	}

	// 安装apk
	protected void installApk(File file) {
		Intent intent = new Intent();
		// 执行动作
		intent.setAction(Intent.ACTION_VIEW);
		// 执行的数据类型
		intent.setDataAndType(Uri.fromFile(file),
				"application/vnd.android.package-archive");
		startActivity(intent);
	}

	/*
	 * 获取当前程序的版本号
	 */
	private String getVersionName() throws Exception {
		// 获取packagemanager的实例
		PackageManager packageManager = getPackageManager();
		// getPackageName()是你当前类的包名，0代表是获取版本信息
		PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(),
				0);
		return packInfo.versionName;
	}

	
	
	//SlindingMenu的关闭监听
	@Override
	public void onClosed() {
		//头部的viewpager在侧滑关闭后，需从新调用开始方法
		if (pager != null) {
			pager.startAutoScroll(4000);
		}
	}

	class PageAdapter extends PagerAdapter {
		@Override
		public int getCount() {
			return imgs.length;
		}

		@Override
		public boolean isViewFromObject(View view, Object o) {
			return view == o;
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			ImageView view = new ImageView(container.getContext());
			view.setScaleType(ImageView.ScaleType.CENTER_CROP);
			imageLoader.displayImage(imgs[position], view,
					options);
			container.addView(view);
			return view;
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView((View) object);
		}

	}

	@Override
	public void onDismiss(ActionSheet actionSheet, boolean isCancel) {

	}

	@Override
	public void onOtherButtonClick(ActionSheet actionSheet, int index) {
		// 检测是否有sd卡
		if (!CoFileUtil.haveSDCard()) {
			return;
		}
		// sd卡剩余容量大于5M
		if (CoFileUtil.getSDFreeSize() < 5) {
			return;
		}

		// 自定义的uri 创建，用于保存保存拍照后的图片，（存在sd卡）
		try {

			File dir = new File(cacheDir);
			if (!dir.exists()) {
				dir.mkdirs(); // 创建文件夹
			}
			String fileName = cacheDir + "/"
					+ cacheImageMame[viewPagerImagePosition];
			File file = new File(fileName);
			file.delete();
			if (!file.exists()) {
				file.createNewFile();// 创建文件
			}
			uri = Uri.fromFile(file);
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (index == 0) {
			// 调用相机
			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
			startActivityForResult(intent, REQUEST_CAMERA);
		} else if (index == 1) {
			// 相册的选择
			Intent picture = new Intent(
					Intent.ACTION_PICK,
					android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
			startActivityForResult(picture, REQUEST_PICTURE);

		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, intent);

		if (requestCode == PHOTO_CODE) {
			// 裁剪的回调
//			pagerAdapter.notifyDataSetChanged();
//			ImageLoader.getInstance().clearDiscCache();
//			ImageLoader.getInstance().clearMemoryCache();
			pager.setAdapter(pagerAdapter);
			pager.startAutoScroll(4000);
		}
		if (requestCode == REQUEST_CAMERA) {
			// 开始拍照的裁剪 （uri为自定义）
			startPhotoZoom(uri);
		}
		if (requestCode == REQUEST_PICTURE && intent != null) {
			// 根据系统相册返回的uri 进行图片裁剪
			startPhotoZoom(intent.getData());
		}

	}

	public void startPhotoZoom(Uri uri1) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri1, "image/*");
		intent.putExtra("crop", "true");// crop=true 有这句才能出来最后的裁剪页面.
		intent.putExtra("aspectX", 8);// 这两项为裁剪框的比例.
		intent.putExtra("aspectY", 5);// 
		intent.putExtra("output", uri);
		intent.putExtra("outputFormat", "JPEG");// 返回格式
		startActivityForResult(intent, PHOTO_CODE);
	}
	
	
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(receiver);// 销毁
	}

	

	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			if(intent.getAction().equals(BluetoothHandler.ACTION_DATA)){
				
				BluetoothPacket packet=(BluetoothPacket) intent.getSerializableExtra("packet");
				if(packet.getType()==BluetoothType.DATA_STEP_MOTHER){
					final int steps=BluetoothUtil.getSteps(packet);
				}else if(packet.getType()==BluetoothType.DATA_TEMPERATURE){
					//这个比较麻烦。。
					LoginUser user=UserCache.getOauth(MainActivity.this);
					if(user.getChildlist().size()>0){
						Child child=user.getChildlist().get(user.childPosition);
						//if(child.getDeviceNo().equals(other))
						String deviceNo=child.getDeviceNo();
						if(deviceNo!=null&&deviceNo.length()==5&&deviceNo.contains(":")){
							String[] devcode=deviceNo.split(":");
							int part1=Integer.valueOf(devcode[0],16);
							int part2=Integer.valueOf(devcode[1],16);
							if(packet.getData()[0]==(byte)part1&&packet.getData()[1]==(byte)part2){
								//孩子匹配成功
								int temp=((packet.getData()[4] & 0xFF) <<8) | (packet.getData()[5] & 0xFF);//byte转int
								double temperature=temp/10;
								if(temperature>38){
									circlelayout.setDrawable(R.drawable.status_danger_ill);
								}else{
									circlelayout.setDrawable(R.drawable.status_normal);
								}
								/*
								if(temperature!=null){
									double[] newarray=new double[temperature.length+1];
									System.arraycopy(temperature, 0, newarray, 1, temperature.length);
									int temp=((packet.getData()[4] & 0xFF) <<8) | (packet.getData()[5] & 0xFF);//byte转int
									newarray[0]=temp/10;
									temperature=newarray;
									setLine(temperature);
								}*/
							}
							
						}
					}
				}
				
			}
		}
	};

	
	

}
